﻿using Quartz;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using General.Core.Common;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Net.Http;

namespace General.Mvc.Jobs
{
    public class RequestUrlJob : IJob
    {
        private readonly ILogger<RequestUrlJob> logger;

        public RequestUrlJob(ILogger<RequestUrlJob> logger)
        {
            this.logger = logger;
        }


        public Task Execute(IJobExecutionContext context)
        {
            var jobData = context.JobDetail.JobDataMap;//获取Job中的参数
            var url = jobData.GetString("url");

            return Task.Run(async () =>
            {
                Stopwatch stopwatch = Stopwatch.StartNew();
                var httpclientHandler = new HttpClientHandler();
                httpclientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true;
                using (HttpClient client = new HttpClient(httpclientHandler))
                {
                    HttpResponseMessage response = await client.GetAsync(url);
                    var resContent = await response.Content.ReadAsStringAsync();

                    resContent = StringExtension.HtmlEncode(resContent);
                    var timeElapsed = stopwatch.Elapsed;
                    logger.LogInformation(new Exception("结果:"+ response.StatusCode.ToString()+ " 响应内容:"+ resContent.Substring(0, resContent.Length>100?100: resContent.Length)), "定时任务访问Url " + url + " 耗时:" + timeElapsed.Milliseconds.ToString() + "ms");
                }
            });
        }
    }
}
